package br.ufpb.di.knowledgetv.sqtv.tests;

import com.googlecode.jcsv.annotations.MapToColumn;
import com.googlecode.jcsv.writer.CSVEntryConverter;
import org.apache.commons.lang.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * User: manoel
 * Date: 20/09/13
 */
public class ResultEntryConverter implements CSVEntryConverter<ResultCSV> {
    @Override
    public String[] convertEntry(ResultCSV resultCSV) {

        List<Field> fields = new ArrayList<Field>();
        for (Field field : resultCSV.getClass().getDeclaredFields()) {
            for (Annotation annotation : field.getDeclaredAnnotations()) {
                if (annotation instanceof MapToColumn) {
                    fields.add(field);
                    break;
                }
            };
        };
        String[] columns = new String[fields.size()];
        for (Field field : fields) {
            int column = field.getAnnotation(MapToColumn.class).column();
            String getName = "get" + StringUtils.capitalize(field.getName());
            try {
                Method method = resultCSV.getClass().getDeclaredMethod(getName);
                    columns[column] = String.valueOf(method.invoke(resultCSV));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return columns;
    };
}
